<template>
	<v-md-editor v-model="state.text" :disabled-menus="[]" @upload-image="handleUploadImage" :loading="state.loading"
		:style="state.style" :mode="state.mode"></v-md-editor>
</template>

<script setup lang="ts" name="wngEditor">
/**
 * 未完全封装，使用请参考文档
 * https://code-farmer-i.github.io/vue-markdown-editor/zh/
 * */

import axios from 'axios';
import { defineProps, reactive } from 'vue';
import { Session } from '/@/utils/storage';
import { ElMessage } from 'element-plus';



// 定义父组件传过来的值
const props = defineProps({
	text: {
		type: String,
		default: '# Ruoyi-Vue3-Plus\n## 此项目时基于Ruoyi-Vue-Plus开发的后台管理系统\n### 后端项目地址：[https://gitee.com/dromara/RuoYi-Vue-Plus](https://gitee.com/dromara/RuoYi-Vue-Plus)\n### 前端项目地址：[https://gitee.com/thiszhc/Ruoyi-Vue3-UI](https://gitee.com/thiszhc/Ruoyi-Vue3-UI)\n### 在此感谢前端vue-naxt-admin团队的开源项目',
	},
	mode: {
		type: String,
		default: 'editable',
	},
	themeConfig: {
		type: Object,
		default: () => {
			return {
				height: "500px",
			};
		},
	},

});

const state = reactive({
	loading: false,
	// 设置上传的请求头部
	headers: { Authorization: "Bearer " + Session.getToken() },
	// 上传的地址
	url: import.meta.env.VITE_API_URL + "/system/oss/upload",
	text: props.text,
	mode: props.mode,
	style: props.themeConfig,
});

/**
 * 上传图片
 * @param {Object} file	上传的文件
 */
const handleUploadImage = async (event: any, insertImage: any, files: any) => {
	return new Promise((resolve, reject) => {
		state.loading = true;
		const formData = new FormData();
		formData.append("file", files[0]);
		axios.post(
			state.url,
			formData, {
			headers: state.headers,
		}).then(res => {
			if (res.data.code === 200) {
				insertImage({
					url: res.data.data.url,
					desc: res.data.data.fileName,
					width: "auto",
					height: "auto",
				});
				ElMessage.success(res.data.msg);
				resolve(insertImage);
			} else {
				ElMessage.error(res.data.msg);
				reject(res.data.msg);
			}
		}).catch(err => {
			ElMessage.error(err);
			reject(err);
		}).finally(() => {
			state.loading = false;
		});
	});
};
</script>
